<template>
  <a-modal
    v-model="isModalVisible"
    :mask-closable="false"
    title="自定义拆分"
    class="split-column"
    cancel-text="取消"
    ok-text="拆分"
    @ok="onOk"
    @cancel="onCancel"
  >
    <p>应如何拆分此数据？</p>
    <a-row class="row">
      <a-col :span="4" class="label">
        使用分隔符
      </a-col>
      <a-col :span="16" :class="{ 'has-error': hasError }">
        <a-input
          ref="inputSeparator"
          v-model="separator"
          placeholder="例如：-,."
        /><br />
        <span v-show="hasError" class="error-message">请输入分隔符</span>
      </a-col>
    </a-row>
    <a-row class="row">
      <a-col :span="4" class="label">
        拆分
      </a-col>
      <a-col :span="16">
        <a-select
          default-value="1"
          :value="`${splitType}`"
          class="select"
          @change="handleSplitTypeChange"
        >
          <a-select-option value="1">
            前
          </a-select-option>
          <a-select-option value="2">
            后
          </a-select-option>
          <a-select-option value="3">
            全部
          </a-select-option>
        </a-select>

        <a-select
          default-value="1"
          class="select"
          :value="`${splitNum}`"
          :disabled="splitType === 3"
          @change="handleSplitNumberChange"
        >
          <a-select-option v-for="item in options" :key="item" :value="item">
            {{ item }}
          </a-select-option>
        </a-select>
        字段
      </a-col>
    </a-row>
  </a-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { IColumn, IKeyValueStore } from '@/store/modules/dataview'
import { apiGetRecommendSplit } from '@/api/data-clean'
import { StatisticsAction } from '@/util/data-selection-actions'

@Component
export default class SplitColumn extends Vue {
  @Prop() column!: IColumn
  @Prop() tableName!: string
  @Prop() taskId!: string
  @Prop() editData!: any
  @Prop({ default: false }) isEdit!: boolean
  @Prop({ default: '' }) parentTableName!: boolean
  private isModalVisible: boolean = true
  private options: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  private splitType: number = 1
  private splitNum: number = 1
  private separator: string = ''
  private hasError: boolean = false

  private handleSplitTypeChange(value: string) {
    this.splitType = +value
  }

  private handleSplitNumberChange(value: string) {
    this.splitNum = +value
  }

  private get formatDescription() {
    let description = `分隔符${this.separator}，拆分`
    if (this.splitType === 3) {
      description += '全部'
    } else {
      description += `${this.splitType === 1 ? '前' : '后'}${
        this.splitNum
      }个字段`
    }
    return description
  }

  mounted() {
    if (this.column.desc && ['varchar', 'text'].includes(this.column.desc)) {
      this.getRecommendSplit()
    }
    this.$nextTick(() => {
      // @ts-ignore
      this.$refs.inputSeparator.focus()
    })
  }

  @Watch('editData', { immediate: true, deep: true })
  private onCurrentHistory(newValue: IKeyValueStore) {
    if (!newValue || !this.isEdit) {
      return
    }
    const history = newValue.data
    if (
      history.actionType === StatisticsAction.splitColumn &&
      history.col === this.column.name
    ) {
      this.separator = history.separator
      this.splitType = history.splitType
      this.splitNum = history.splitNum
    }
  }

  // 获取推荐的分隔符
  async getRecommendSplit() {
    const response = await apiGetRecommendSplit({
      data: {
        table: this.tableName,
        type: this.column.type,
        name: this.column.name,
        taskId: this.taskId,
      },
    })
    const { separators } = response.data.result || {}
    if (separators && separators.length > 0 && !this.editData.data.separator) {
      ;[this.separator] = separators
    }
  }

  onOk() {
    if (!this.separator) {
      return
    }
    this.emitSplitParams()
  }

  onCancel() {
    this.$emit('on-filter-params-change', null)
    this.$emit('config-cancel')
    this.isModalVisible = false
  }

  private onInputChange(event: any) {
    const value = event.target.value.trim()
    if (!value) {
      this.hasError = true
    } else {
      this.hasError = false
    }
  }

  /**
   * 抛出去清洗动作参数
   */
  private emitSplitParams() {
    this.$emit('on-filter-params-change', {
      data: {
        action: 'SPLIT',
        col: this.column.name,
        columnName: this.column.name,
        separator: this.separator,
        splitType: this.splitType,
        splitNum: this.splitNum,
        description: this.formatDescription,
        actionType: StatisticsAction.splitColumn,
      },
    })
  }
}
</script>

<style lang="less" scoped>
.split-column {
  .row {
    margin-top: 14px;
  }

  .label {
    line-height: 30px;
    margin-right: 8px;
    text-align: right;
  }

  .select {
    margin-right: 12px;
    width: 120px;
  }

  .error-message {
    color: #f5222d;
    font-size: 12px;
    line-height: 1.5;
  }
}
</style>
